package com.search;

/**
 * @author cjx
 * @create 2024/06/25
 * @description 二分查找
 */
public class TwoSearch {
    public static void main(String[] args) {
        int[] arr = { 2, 6, 17, 19, 32, 40, 55, 71, 99 };
        twoSeach(arr, 71);
    }

    // 二分查找
    // 前置条件 有序数组
    private static void twoSeach(int[] arr, int number) {
        int min = 0;
        int max = arr.length - 1;
        while (true) {
            int mid = (max + min) / 2;
            if (min > max) {
                System.out.println("数值不存在");
                break;
            }

            if (arr[mid] > number) {
                max = mid - 1;
                System.out.println("max:" + max + "\tmid:" + mid);
            } else if (arr[mid] < number) {
                min = mid + 1;
                System.out.println("min:" + mid + "\tmid:" + mid);
            } else {
                System.out.println("index:" + mid + "\tnum:" + arr[mid]);
                break;
            }
        }
    }
}
